package com.qdhh.enrollment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qdhh.enrollment.domain.Milestone;
import com.qdhh.enrollment.dto.MilestoneDTO;
import com.qdhh.enrollment.mapper.MilestoneMapper;
import com.qdhh.enrollment.service.MilestoneService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MilestoneServiceImpl implements MilestoneService {

    private final MilestoneMapper milestoneMapper;
    private static final DateTimeFormatter DF = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public List<MilestoneDTO> list(String type, Integer limit) {
        try {
            LambdaQueryWrapper<Milestone> wrapper = new LambdaQueryWrapper<Milestone>()
                .eq(Milestone::getEnabled, 1)
                .orderByAsc(Milestone::getDate)
                .orderByAsc(Milestone::getOrderNum);

            if (type != null && !type.isEmpty()) {
                wrapper.eq(Milestone::getType, type);
            }
            if (limit != null && limit > 0) {
                wrapper.last("LIMIT " + limit);
            }

            List<Milestone> milestones = milestoneMapper.selectList(wrapper);
            if (milestones == null) {
                return new java.util.ArrayList<>();
            }

            return milestones.stream()
                .map(m -> {
                    if (m == null) {
                        return null;
                    }
                    MilestoneDTO dto = new MilestoneDTO();
                    dto.setId(m.getId());
                    dto.setTitle(m.getTitle());
                    dto.setDate(m.getDate() != null ? m.getDate().format(DF) : null);
                    dto.setType(m.getType());
                    dto.setDescription(m.getDescription());
                    dto.setOrderNum(m.getOrderNum());
                    return dto;
                })
                .filter(dto -> dto != null)
                .collect(Collectors.toList());
        } catch (Exception e) {
            // 如果查询失败（例如表不存在），返回空列表而不是抛出异常
            return new java.util.ArrayList<>();
        }
    }
}
